package com.gqz.file.config;

import com.aliyun.oss.*;
import com.aliyun.oss.common.comm.RequestMessage;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.common.comm.RetryStrategy;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 阿里云oss配置
 *
 * @author gqz20
 * @date 2023/02/10
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "aliyun")
public class OssConfig {

    /**
     * 访问密钥id
     */
    private String accessKeyId;


    /**
     * 秘密访问密钥
     */
    private String secretAccessKey;


    /**
     * 终点
     */
    private String endPoint;


    /**
     * bucket名称
     */
    private String bucketName;

    @Bean
    protected OSS ossClient() {
        // 添加oss客户端配置
        ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
        configuration.setRetryStrategy(new RetryStrategy() {
            @Override
            public boolean shouldRetry(Exception e, RequestMessage requestMessage, ResponseMessage responseMessage, int i) {
                String errorCode;
                if (e instanceof ClientException) {
                    errorCode = ((ClientException) e).getErrorCode();
                    if (errorCode.equals("ConnectionTimeout") || errorCode.equals("SocketTimeout") || errorCode.equals("ConnectionRefused") || errorCode.equals("UnknownHost") || errorCode.equals("SocketException") || errorCode.equals("SslException")) {
                        return true;
                    }

                    if (errorCode.equals("NonRepeatableRequest")) {
                        return false;
                    }
                }

                if (e instanceof OSSException) {
                    errorCode = ((OSSException) e).getErrorCode();
                    if (errorCode.equals("InvalidResponse")) {
                        return false;
                    }
                }

                if (responseMessage != null) {
                    int statusCode = responseMessage.getStatusCode();
                    if (statusCode == 500 || statusCode == 502 || statusCode == 503) {
                        return true;
                    }
                }

                return false;
            }
        });

        OSS client = new OSSClientBuilder()
                .build(endPoint, accessKeyId, secretAccessKey, configuration);
        return client;
    }
}
